from asyncio import Task
from fastapi import FastAPI
from pydantic import BaseModel
from typing import List
from datetime import datetime

from tasks import r, task_demo
from models import Tasks

app = FastAPI()

class TasksInfo(BaseModel):

    # 任务id列表
    task_id_list: List[str] = []

@app.post('/get-tasks-info')
def get_tasks_info(params: TasksInfo):
    
    return {
        'status': 'success',
        'task_info': [
            {
                'task_id': task_id,
                'create_datetime': list(Tasks.select().where(Tasks.task_id == task_id).dicts())[0]['create_datetime'],
                'task_progress': float(r.get(f'task-progress-{task_id}') or 0)
            }
            for task_id in params.task_id_list
        ]
    }

@app.get('/create-new-task')
def create_new_task():

    new_task = task_demo.delay()

    Tasks.create(
        task_id=new_task.id,
        create_datetime=datetime.now()
    )

    return {
        'status': 'success',
        'task_id': new_task.id
    }

@app.get('/get-all-tasks-id')
def get_all_tasks_id():

    return {
        'status': 'success',
        'data': [
            item['task_id']
            for item in
            Tasks.select().dicts()
        ]
    }

'''uvicorn app:app --reload --host=127.0.0.1 --port=8000'''